//
//  YbrSystemUtil.m
//  wifibox
//
//  Created by os X 10.9 on 15-2-10.
//  Copyright (c) 2015年 yinbaner. All rights reserved.
//


#include <arpa/inet.h>
#include <netdb.h>
#include <net/if.h>
#include <ifaddrs.h>
#import <dlfcn.h>
#import <SystemConfiguration/CaptiveNetwork.h>
#import <sys/utsname.h>

#import "YbrSystemUtil.h"


@implementation YbrSystemUtil


// 获取当前网络状态
+(NetworkStatus)GetCurrntNet
{
    Reachability * r    =   [Reachability reachabilityWithHostname:@"www.baidu.com"];
    return [r currentReachabilityStatus];
}


// 获取当前设备的ID
+(NSString *) getDeviceID
{
    NSUserDefaults * defaults   =   [NSUserDefaults standardUserDefaults];
    NSString * value            =   [defaults objectForKey:@"DeviceId"];
    return value;
}


// 获取当前设备的name
+(NSString *) getDeviceName
{
    NSString * userPhoneName    =   [[UIDevice currentDevice] name];    
    NSString * phoneModel       =   [[UIDevice currentDevice] model];
    
    return [NSString stringWithFormat:@"%@ - %@" ,userPhoneName , phoneModel];
}


// 获取设备当前的IP
+(NSString *) getDeviceCurrentIpAddress
{
    BOOL success;
    struct ifaddrs * addrs;
    const struct ifaddrs * cursor;
    
    success         =   getifaddrs(&addrs) == 0;
    if (success) {
        cursor      =   addrs;
        while (cursor != NULL) {
            // the second test keeps from picking up the loopback address
            if (cursor->ifa_addr->sa_family == AF_INET && (cursor->ifa_flags & IFF_LOOPBACK) == 0)
            {
                NSString *name = [NSString stringWithUTF8String:cursor->ifa_name];
                if ([name isEqualToString:@"en0"])  // Wi-Fi adapter
                    return [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)cursor->ifa_addr)->sin_addr)];
            }
            cursor = cursor->ifa_next;
        }
        
        freeifaddrs(addrs);
    }
    return nil;
}


// 获取手机连接当前WiFi的名称
+(NSString *) getCurrentConnectedWifiName
{
    NSString * wifiName             =   nil;
    CFArrayRef wifiInterfaces       =   CNCopySupportedInterfaces();
        
    if (!wifiInterfaces) {
        return nil;
    }
        
    NSArray *interfaces             =   (__bridge NSArray *) wifiInterfaces;
        
    for (NSString *interfaceName in interfaces) {
        CFDictionaryRef dictRef     =   CNCopyCurrentNetworkInfo((__bridge CFStringRef)(interfaceName));
            
        if (dictRef) {
            NSDictionary *networkInfo = (__bridge NSDictionary *)dictRef;
//            NSLog(@"network info -> %@", networkInfo);//输出
            wifiName = [networkInfo objectForKey:(__bridge NSString *)kCNNetworkInfoKeySSID];
                
            CFRelease(dictRef);
        }
    }
    CFRelease(wifiInterfaces);
    return wifiName;
}


// 获得当前连接的wifi的SSID
+(NSString *)currentWifiSSID
{
    CFArrayRef myArray          =   CNCopySupportedInterfaces();
    CFDictionaryRef myDict      =   CNCopyCurrentNetworkInfo(CFArrayGetValueAtIndex(myArray, 0));
    NSDictionary *myDictionary  =   (__bridge NSDictionary*)myDict;
    NSString * SSID             =   [myDictionary objectForKey:@"SSID"];
    return SSID;
}


// 获取UUID
+(NSString *)getCFuuid
{
    CFUUIDRef cfuuid = CFUUIDCreate(kCFAllocatorDefault);
    NSString *cfuuidString = (NSString*)CFBridgingRelease(CFUUIDCreateString(kCFAllocatorDefault, cfuuid));
    NSString *str = [cfuuidString stringByReplacingOccurrencesOfString:@"-" withString:@""];
    return str;
}

+(NSString *)getDeviceIphone
{
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString *deviceString = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
    return deviceString;
 
}


// json转String
+(NSString *)jsonToString:(id)json
{
    NSError * error     =   nil;
    NSData *jsonData    =   [NSJSONSerialization dataWithJSONObject:json
                                                            options:NSJSONWritingPrettyPrinted
                                                              error:& error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    if (error == nil) {
         //NSLog(@"----yyyyyyyyyyyyyyyyyyyyy-------格式化json----%@",jsonString);
        return jsonString;
    }else{
        return nil;
    }
}

// String装json
+(instancetype)stringToJson:(NSString *)string
{
    
    NSError * error     =   nil;
    NSData *data        =   [string dataUsingEncoding:NSUTF8StringEncoding];
    id JsonObject=[NSJSONSerialization JSONObjectWithData:data
                                                  options:NSJSONReadingAllowFragments
                                                    error:& error];
    
    if (error == nil) {
        return JsonObject;
    }else{
        return nil;
    }
}


// 检测手机号码是不是符合格式
+(BOOL)checkTel:(NSString *)str
{
    if ([str length] == 0) {
        return NO;
    }
    NSString *regex     =   @"^(([1-9][0-9][0-9]))\\d{8}$";
    NSPredicate *pred   =   [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isMatch        =   [pred evaluateWithObject:str];
    if (!isMatch) {
        return NO;
    }
    return YES;
}


+(UIFont *) getUIFont:(int)fontsize
{
    return [UIFont fontWithName:@"Helvetica-Bold" size:fontsize];
}


// 获取字体的宽度高度
+(CGSize)getTextSize:(NSString *)text  font:(UIFont *)font
{
    CGSize textSize = CGSizeMake(0, 0);
    NSDictionary *attributes = @{NSFontAttributeName:font,};
    textSize = [text boundingRectWithSize:CGSizeMake(MAXFLOAT, MAXFLOAT) options:NSStringDrawingTruncatesLastVisibleLine attributes:attributes context:nil].size;;
    return textSize;
}
@end






